package com.originskyseed.platform.cms.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.cms.i18n.CmsResponseMsg;
import com.originskyseed.platform.cms.model.AnchorRelatePlayerVO;
import com.originskyseed.platform.cms.model.GiftRelateReceive;
import com.originskyseed.platform.cms.model.GiftRelateReceiveReview;
import com.originskyseed.platform.cms.service.IGiftRelateReceiveReviewService;
import com.originskyseed.platform.cms.service.IGiftRelateReceiveService;
import com.originskyseed.platform.cms.vo.request.AnchorRelatePlayerRequestVO;
import com.originskyseed.platform.cms.vo.request.GiftRelateReceiveRequestVO;
import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 礼品领取信息Controller类（OSI_GIFT_RELATE_RECEIVE）
 *
 * @author WuZhuoXi
 */
@Controller
@RequestMapping("/giftRelateReceive")
@BaseLocaleResource(localeFileName = "i18n_cms")
public class GiftRelateReceiveController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(GiftRelateReceiveController.class);

	@DubboReference
	private IGiftRelateReceiveService giftRelateReceiveService;

	@DubboReference
	private IGiftRelateReceiveReviewService giftRelateReceiveReviewService;
	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/giftRelateReceiveList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<GiftRelateReceive>> giftRelateReceiveList(HttpServletRequest request) {
		BaseResponseBody<BasePage<GiftRelateReceive>> result = null;
		try {
			// 请求对象
			GiftRelateReceiveRequestVO requestVO = this.getParameterBean(GiftRelateReceiveRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// requestVO.setCreatorId(userInfo.getId());
			if(userInfo.getSourceSys()!=0)
			{
				if (userInfo.getType() == 6 || userInfo.getType() == 11)// 标识主播或是业务员,只能查看自己的
				{
					requestVO.setDeptId("");
				} else {
					requestVO.setDeptId(userInfo.getDeptId());
				}
				requestVO.setApplyId(userInfo.getId());
			}
			// 分页查询
			BasePage<GiftRelateReceive> page = new BasePage<GiftRelateReceive>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.giftRelateReceiveService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<GiftRelateReceive>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<GiftRelateReceive>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 艺人维护情况
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectAnchorRelatePlayerList.json")
	@RequiredParams(names = { "pageNo", "pageSize","playerId" })
	public BaseResponseBody<BasePage<AnchorRelatePlayerVO>> selectAnchorRelatePlayerList(HttpServletRequest request) {
		BaseResponseBody<BasePage<AnchorRelatePlayerVO>> result = null;
		try {
			// 请求对象
			AnchorRelatePlayerRequestVO requestVO = this.getParameterBean(AnchorRelatePlayerRequestVO.class);
			// 分页查询
			BasePage<AnchorRelatePlayerVO> page = new BasePage<AnchorRelatePlayerVO>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.giftRelateReceiveService.selectAnchorRelatePlayerListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<AnchorRelatePlayerVO>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<AnchorRelatePlayerVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 物料登记列表导出Excel
	 *
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/exportToExcel.json")
	@SysLog(module = "物料登记列表", operationDesc = "物料登记列表信息")
	public void exportToExcel(HttpServletRequest request, HttpServletResponse response) {
		try {
			// 请求对象
			GiftRelateReceiveRequestVO requestVO = this.getParameterBean(GiftRelateReceiveRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			requestVO.setCreatorId(userInfo.getId());
			List<GiftRelateReceive> list = this.giftRelateReceiveService.selectListToExcel(requestVO.toMap());

			// excel标题
			String[] title = { "用户ID(*)", "用户昵称 (*)", "主播ID (*)", "礼品图片地址 (*)", "物料名称 (*)", "申请数量 (*)", "申请人 (*)", "申请时间 (*)", "审核状态 (*)", "审核时间 (*)" };
			// excel文件名
			String fileName = "物料登记列表" + System.currentTimeMillis() + ".xls";
			// sheet名
			String sheetName = "物料登记";
			String[][] values = new String[list.size()][];
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			if (list != null && list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					values[i] = new String[title.length];
					GiftRelateReceive obj = list.get(i);
					values[i][0] = obj.getPlayerId();
					values[i][1] = obj.getPlayerNickName();
					values[i][2] = obj.getAnchorId();
					values[i][3] = obj.getPath() == null ? "" : obj.getPath();
					values[i][4] = obj.getName() == null ? "" : obj.getName();
					values[i][5] = obj.getNum().toString();
					values[i][6] = obj.getApplyName();
					values[i][7] = format.format(obj.getApplyTime());
					// 审核状态（0:待审核 1:审核不通过 2:审核通过）
					if (obj.getReviewStatus() == 0) {
						values[i][8] = "待审核";
					} else if (obj.getReviewStatus() == 1) {
						values[i][8] = "审核不通过";
					} else if (obj.getReviewStatus() == 2) {
						values[i][8] = "审核通过";
					} else {
						values[i][8] = "";
					}
					values[i][9] = obj.getReviewTime() == null ? "" : format.format(obj.getReviewTime());
				}
			}
			outPutExcel(response, title, fileName, sheetName, values);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 输出Excel
	 *
	 * @param response
	 * @param title
	 * @param fileName
	 * @param sheetName
	 * @param values
	 * @throws IOException
	 */
	private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
		// 创建HSSFWorkbook
		HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		// 将文件存到指定位置
		this.setResponseHeader(response, fileName);
		OutputStream os = response.getOutputStream();
		wb.write(os);
		os.flush();
		os.close();
	}

	/**
	 * 发送响应流方法
	 *
	 * @param response
	 * @param fileName
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.error(e.getMessage(), e);
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error(ex.getMessage(), ex);
		}
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/giftRelateReceiveSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<GiftRelateReceive> giftRelateReceiveSave(HttpServletRequest request) {
		BaseResponseBody<GiftRelateReceive> result = null;
		try {
			// 请求对象
			GiftRelateReceive giftRelateReceive = this.getParameterBean(GiftRelateReceive.class);

			if (StringUtils.isNotBlank(giftRelateReceive.getId())) {
				// 发货时间
				if (giftRelateReceive.getIsDeliver() == 0) {
					giftRelateReceive.setDeliverTime(new Date());
				}
				this.giftRelateReceiveService.updateByPrimaryKeySelective(giftRelateReceive);
			} else {
				UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
				giftRelateReceive.setCreatorId(userInfo.getId());
				giftRelateReceive.setCreator(userInfo.getName());
				giftRelateReceive.setIsDeliver(1);

				giftRelateReceive.setApplyId(userInfo.getId());
				giftRelateReceive.setApplyName(userInfo.getName());
				giftRelateReceive.setApplyTime(new Date());
				this.giftRelateReceiveService.insertSelective(giftRelateReceive);
			}
			result = new BaseResponseBody<GiftRelateReceive>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CONTENTAUDIT_SUCCESS.getMsg()), giftRelateReceive);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<GiftRelateReceive>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CONTENTAUDIT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/giftRelateReceiveDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> giftRelateReceiveDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.giftRelateReceiveService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CONTENTAUDIT_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CONTENTAUDIT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/giftRelateReceiveDetails.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody<GiftRelateReceive> giftRelateReceiveDetails(HttpServletRequest request) {
		BaseResponseBody<GiftRelateReceive> result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			GiftRelateReceive giftRelateReceive = this.giftRelateReceiveService.selectByPrimaryKey(id);
			if (giftRelateReceive != null) {
				giftRelateReceive.setIsRead(2);
				giftRelateReceive.setApplyId(userInfo == null ? "" : userInfo.getId());
				this.giftRelateReceiveService.updateByPrimaryKeySelective(giftRelateReceive);
			}
			result = new BaseResponseBody<GiftRelateReceive>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_SUCCESS.getMsg()), giftRelateReceive);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<GiftRelateReceive>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 审核
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/audit.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody<GiftRelateReceiveReview> audit(HttpServletRequest request) {
		BaseResponseBody<GiftRelateReceiveReview> result = null;
		try {
			// 请求对象
			GiftRelateReceiveReview giftRelateReceiveReview = this.getParameterBean(GiftRelateReceiveReview.class);
			giftRelateReceiveReview.setReviewTime(new Date());
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			giftRelateReceiveReview.setCreator(userInfo == null ? "" : userInfo.getName());
			giftRelateReceiveReview.setCreatorId(userInfo == null ? "" : userInfo.getId());
			this.giftRelateReceiveReviewService.insertSelective(giftRelateReceiveReview);

			GiftRelateReceive giftRelateReceive = new GiftRelateReceive();
			giftRelateReceive.setId(giftRelateReceiveReview.getGiftReceiveId());
			if (giftRelateReceiveReview.getReviewStatus() == 1) {
				giftRelateReceive.setReviewStatus(0);
			}
			this.giftRelateReceiveService.updateByPrimaryKeySelective(giftRelateReceive);
			result = new BaseResponseBody<GiftRelateReceiveReview>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CONTENTAUDIT_SUCCESS.getMsg()), giftRelateReceiveReview);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<GiftRelateReceiveReview>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CONTENTAUDIT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 审核
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/isRead.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody<GiftRelateReceive> isRead(HttpServletRequest request) {
		BaseResponseBody<GiftRelateReceive> result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			GiftRelateReceive giftRelateReceive = giftRelateReceiveService.selectByPrimaryKey(id);
			if (giftRelateReceive != null) {
				giftRelateReceive.setIsRead(2);
				this.giftRelateReceiveService.updateByPrimaryKeySelective(giftRelateReceive);
			}
			result = new BaseResponseBody<GiftRelateReceive>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CONTENTAUDIT_SUCCESS.getMsg()), giftRelateReceive);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<GiftRelateReceive>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CONTENTAUDIT_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}
}
